<template>
  <div v-loading="loading" class="parentStyle">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <div class="area-header">
          <span class="area-header-title">{{ $t('工商信息') }}</span>
        </div>
        <el-col :span="12">
          <el-form-item :label="$t('管理人全称')" prop="name">
            <el-autocomplete
              v-model="form.name"
              class="inline-input name"
              :fetch-suggestions="companyQuerySearch"
              :placeholder="$t('管理人全称')"
              :trigger-on-focus="false"
              :maxlength="100"
              @select="companyHandleSelect"
            >
              <template v-if="enableTyc" slot="append">
                <a @click="companyHandleSelect">{{ $t('查询工商信息') }}</a>
              </template>
            </el-autocomplete>
            <!-- <el-input v-else v-model="form.name" readonly show-word-limit maxlength="100"> -->
            <!-- <template slot="append">
                <a @click="companyHandleSelect">{{ $t('查询工商信息') }}</a>
              </template> -->
            <!-- </el-input> -->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('管理人简称')" prop="shortName">
            <el-input v-model="form.shortName" :placeholder="$t('管理人简称')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col v-if="getShowEn" :span="12">
          <el-form-item :label="$t('管理人全称En')" prop="nameEn">
            <el-input v-model="form.nameEn" :placeholder="$t('管理人全称En')" show-word-limit maxlength="500" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('企业统一社会信用代码')" prop="creditCode">
            <el-input v-model="form.company.creditCode" :placeholder="$t('企业统一社会信用代码')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('管理人编码')" prop="pCode">
            <el-input v-model="form.pCode" :placeholder="$t('P码')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('法定代表人')" prop="legalRepresentative">
            <el-input v-model="form.company.legalPerson" :placeholder="$t('法定代表人')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('成立时间')" prop="setDate">
            <DatePicker v-model="form.company.setDate" :placeholder="$t('成立时间')" />
          </el-form-item>
        </el-col>
        <!--行业-->
        <Industry ref="industryZj" :buss-data="form.company" />
        <!--地域-->
        <Area ref="cityZj" :buss-data="form.company" />
        <el-col :span="24">
          <el-form-item :label="$t('注册地-详细地址')" prop="detailsRegistered">
            <el-input v-model="form.company.detailsRegistered" :placeholder="$t('注册地-详细地址')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('注册资本') + $t('金额单位')" prop="capitalRegistered">
            <Money v-model="form.company.capitalRegistered" unit="w" :placeholder="$t('注册资本')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('注册资本币种')">
            <el-select v-model="form.company.currency" :placeholder="$t('注册资本币种')" :clearable="true">
              <el-option
                v-for="dict in currencyOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!--        <el-col :span="12">-->
        <!--          <el-form-item :label="$t('上市情况')" prop="listingSituation">-->
        <!--            <dict-select-->
        <!--              v-model="form.company.listedSituation"-->
        <!--              dictionary="bf_group_listed_situation"-->
        <!--            />-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <!--        <el-col :span="12">-->
        <!--          <el-form-item :label="$t('上市板块')" prop="listedSector">-->
        <!--            <dict-select-->
        <!--              v-model="form.company.listedSector"-->
        <!--              dictionary="bf_group_listed_sector"-->
        <!--            />-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <!--        <el-col :span="12">-->
        <!--          <el-form-item :label="$t('股票代码')" prop="stockCode">-->
        <!--            <el-input v-model="form.company.stockCode" show-word-limit maxlength="100" />-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('备注')" show-word-limit maxlength="2000" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="mt-15">
        <el-col :span="24">
          <div class="area-header">
            <span class="area-header-title">{{ $t('管理机构信息') }}</span>
          </div>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('是否完成基金业协会登记')">
            <el-radio-group v-model="form.isConsortiumRegistry">
              <el-radio
                v-for="dict in isConsortiumRegistryOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <div v-if="form.isConsortiumRegistry === 'Y'">
          <el-col :span="12">
            <el-form-item :label="$t('基金业协会登记日期')" prop="dateRegistration">
              <DatePicker
                v-model="form.dateRegistration"
                :placeholder="$t('基金业协会登记日期')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('基金业协会登记编号')" prop="associationNumber">
              <el-input v-model="form.associationNumber" :placeholder="$t('基金业协会登记编号')" show-word-limit maxlength="50" />
            </el-form-item>
          </el-col>
        </div>
        <el-col v-if="busType !== 'GP'" :span="12">
          <el-form-item :label="$t('机构企业性质')">
            <el-select v-model="form.natureEnterprise" :placeholder="$t('机构企业性质')" :clearable="true">
              <el-option
                v-for="(dict, index) in natureEnterpriseOptions"
                :key="index"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="busType !== 'GP'" :span="12">
          <el-form-item :label="$t('机构类型')">
            <el-select v-model="form.organizationType" :placeholder="$t('机构类型')" :clearable="true">
              <el-option
                v-for="dict in organizationTypeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="busType === 'GP'" :span="12">
          <el-form-item :label="$t('是否为执行事务合伙人')">
            <el-radio-group v-model="form.isExecutivePartner">
              <el-radio
                v-for="dict in isExecutivePartnerOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="busType === 'GP'" :span="12">
          <el-form-item :label="$t('是否为投资顾问')">
            <el-radio-group v-model="form.isInvestmentAdvisor">
              <el-radio
                v-for="dict in isInvestmentAdvisorOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('机构组织形式')">
            <el-select v-model="form.organizationForm" :placeholder="$t('机构组织形式')" :clearable="true">
              <el-option
                v-for="dict in organizationFormOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('联系人')" prop="contacts">
            <el-input v-model="form.contacts" :placeholder="$t('联系人')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('联系人职务')" prop="contactPerson">
            <el-input v-model="form.contactPerson" :placeholder="$t('联系人职务')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('联系人电话')" prop="contactPhone">
            <el-input v-model="form.contactPhone" :placeholder="$t('联系人电话')" show-word-limit maxlength="25" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('联系人邮箱')" prop="contactEmail">
            <el-input v-model="form.contactEmail" :placeholder="$t('联系人邮箱')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: center;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <SaveBtn has-permi="fund:gpbase" :cancel-func="cancel" :cancel-show="!this.$route.query.id" />
    </div>
  </div>
</template>

<script>
import { saveGpBase, getGpBase, gpListByName, getGpByName } from '@/api/fund/gp/gpBase'
// 行业组件
import Industry from '@/components/Industry'
// 省市组件
import Area from '@/components/Area'
import { Notification } from 'element-ui'

export default {
  components: {
    Industry,
    Area
  },
  props: {
    busType: {
      type: String,
      required: false,
      default: ''
    }
  },
  data() {
    const checkPhoneAndEmail = (rule, value, callback) => {
      if (value !== undefined && value !== '' && value !== null) {
        // 校验电话
        if (rule.field === 'contactPhone') {
          var regPhone = /^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/
          if (!regPhone.test(value)) {
            callback(new Error(this.$t('号码有误格式不正确：0000-0000000')))
          }
        }
        callback()
      } else {
        callback()
      }
    }
    return {
      enableTyc: undefined,
      // 注册资本币种字典
      currencyOptions: [],
      // 是否上市
      yesOrNoOptions: [],
      // 管理人类型字典
      typeOptions: [],
      // 是否完成基金业协会登记字典
      isConsortiumRegistryOptions: [],
      // 是否为执行事务合伙人字典
      isExecutivePartnerOptions: [],
      // 是否为投资顾问字典
      isInvestmentAdvisorOptions: [],
      // 机构企业性质字典
      natureEnterpriseOptions: [],
      // 机构类型字典
      organizationTypeOptions: [],
      // 机构组织形式字典
      organizationFormOptions: [],
      // 表单参数
      form: {
        company: {}
      },
      // 遮罩层
      loading: false,
      // 天眼查查询条件
      tycParam: {
        id: '',
        name: '',
        shortName: '',
        tycId: ''
      },
      // 表单校验
      rules: {
        name: [{ required: true, message: '必填信息', trigger: 'blur' }],
        shortName: [{ required: true, message: '必填信息', trigger: 'change' }],
        // type: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        dateRegistration: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        associationNumber: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        contactPhone: [{ required: false, validator: checkPhoneAndEmail, trigger: 'blur' }],
        contactEmail: [{ required: false, message: this.$t('必填信息'), trigger: 'blur' }, { type: 'email', message: this.$t('邮箱格式不正确') }]
      }
    }
  },
  computed: {
    getShowEn() {
      if (this.$store.state.app.showEn === 'true') {
        return true
      } else {
        return false
      }
    }
  },
  created() {
    this.getDicts('currency').then(response => {
      this.currencyOptions = response.data
    })
    this.getDicts('fund_manger_type').then(response => {
      this.typeOptions = response.data
    })
    this.getDicts('sys_yes_no').then(response => {
      this.isConsortiumRegistryOptions = response.data
      this.isExecutivePartnerOptions = response.data
      this.isInvestmentAdvisorOptions = response.data
    })
    this.getDicts('manager_enterprise_nature').then(response => {
      this.natureEnterpriseOptions = response.data
    })
    this.getDicts('manager_type').then(response => {
      this.organizationTypeOptions = response.data
    })
    this.getDicts('manager_organizational form').then(response => {
      this.organizationFormOptions = response.data
    })
  },
  mounted() {
    this.$bus.$emit('async_done')
    this.enableTyc = (window.localStorage.getItem('enableTyc') === 'true')
  },
  methods: {
    // 初始化数据
    init(data) {
      this.loading = true
      if (data != null && data.id !== undefined) {
        getGpBase(data.id).then(response => {
          console.log('222')
          if (response.data != null) {
            this.form = response.data
            if (this.form.company === null || this.form.company === undefined) {
              this.form.company = {}
            }
            this.$nextTick(() => {
              this.$refs.industryZj.initIndustrySecond()
              this.$refs.cityZj.initCity()
              this.$refs.cityZj.initDistrict()
            })
          }
          this.loading = false
        })
      } else {
        this.reset()
        this.loading = false
      }
    },
    // 表单重置
    reset() {
      this.form = {
        company: {
          industryFirst: undefined,
          industrySecond: undefined,
          provinceRegistered: undefined,
          cityRegistered: undefined,
          districtRegistered: undefined
        },
        id: undefined,
        name: undefined,
        nameEn: undefined,
        shortName: undefined,
        type: this.$route.query.type,
        busType: this.busType,
        isConsortiumRegistry: 'N',
        dateRegistration: undefined,
        associationNumber: undefined,
        natureEnterprise: undefined,
        organizationType: undefined,
        organizationForm: undefined,
        contacts: undefined,
        contactPerson: undefined,
        contactPhone: undefined,
        contactEmail: undefined,
        PCode: undefined,
        isExecutivePartner: 'N',
        isInvestmentAdvisor: 'N',
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
        // this.$parent.$parent.reset()
      }
      if (this.$parent.$parent.managerOpen !== undefined) {
        this.$parent.$parent.managerOpen = false
      }
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      if (this.$parent.$parent.managerOpen !== undefined) {
        this.$parent.$parent.managerOpen = false
      }
      // 刷新list页面
      this.$parent.$parent.getList()
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loading = true
          saveGpBase(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.$t('保存成功'))
              this.$emit('successSaveManager', response.data)
              this.closeForm()
            } else {
              this.msgError(response.msg)
            }
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        } else {
          this.locationError(document)
        }
      })
    },
    // 标的公司查询
    companyQuerySearch(queryString, cb) {
      gpListByName(queryString).then(res => {
        if (res.code === 200) {
          cb(res.data)
        }
      })
    },
    // 录入管理人简称之后，查询是否已经存在这个管理人
    // 标的公司选择后事件
    companyHandleSelect(item) {
      const name = this.form.name
      if (name === '' || name === undefined) {
        Notification.error({
          title: this.$t('请先输入管理公司全称！！')
        })
        return
      }
      this.tycParam.shortName = item !== undefined ? item.shortName : ''
      if (this.tycParam.shortName === undefined) {
        this.tycParam.shortName = this.form.shortName
      }
      this.tycParam.name = name
      this.tycParam.id = this.form.id
      this.tycParam.type = this.$route.query.type === undefined ? this.form.type : this.$route.query.type
      this.tycParam.busType = this.busType
      getGpByName(this.tycParam).then(res => {
        if (res.data !== null && res.data.id !== null && res.data.id !== '') {
          this.msgError(this.$t('当前管理人已存在，不能重复添加！'))
          this.form.name = ''
          return
        }
        if (item.shortName) {
          this.form.shortName = item.shortName
        }
        this.form.company = res.data.company
        this.form.pCode = res.data.pCode
        if (res.data.pCode) {
          this.form.isConsortiumRegistry = 'Y'
        } else {
          this.form.isConsortiumRegistry = 'N'
        }
        this.form.company.companyShortName = item.shortName
        this.$nextTick(() => {
          if (this.$refs.industryZj?.initIndustrySecond !== undefined) {
            this.$refs.industryZj.initIndustrySecond()
          }
        })
        this.$nextTick(() => {
          if (this.$refs.cityZj?.initCity !== undefined) {
            this.$refs.cityZj.initCity()
          }
          if (this.$refs.cityZj?.initDistrict !== undefined) {
            this.$refs.cityZj.initDistrict()
          }
        })

        // 关联公司ID
        this.form.companyId = res.data.company.id
        this.msgSuccess(this.$t('已获取工商信息！'))
        this.loading = false
      })
    }
  }

}
</script>
